package com.webserver.core;

import com.webserver.annotation.Controller;
import com.webserver.annotation.RequestMapping;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

public class HandlerMapping {
    private static Map<String, Method> mappings = new HashMap<>();
    static {
        iniMapping();
    }

    private static void iniMapping() {
        try {
            File dir = new File(HandlerMapping.class.getClassLoader().getResource("./com/webserver/controller").toURI());
            File[] files = dir.listFiles(f->f.getName().endsWith(".class"));
            for (File file : files){
                String flieName = file.getName();
                String className = flieName.substring(0,flieName.indexOf("."));
                String packageName = dir.getName();
                Class cls = Class.forName("com.webserver.controller."+className);
                if (cls.isAnnotationPresent(Controller.class)){
                    Object obj = cls.newInstance();
                    Method[] methods = cls.getDeclaredMethods();
                    for (Method m : methods){
                        if (m.isAnnotationPresent(RequestMapping.class)){
                            RequestMapping rm = m.getAnnotation(RequestMapping.class);
                            String para = rm.value();
                           mappings.put(para,m);
                        }
                    }

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Method getMethod(String path){
        return mappings.get(path);
    }

    public static void main(String[] args) {
        Method m = mappings.get("/regUser");
        System.out.println(m);
    }
}
